var k_edit = true;
var url;
$(window).load(function() {
	if ($.datepicker) {
		$(".edit_datepicker").each(function(){
			var pattern = 'dd/mm/yy';
			var this_pattern = $(this).attr('pattern');
			if (this_pattern){
				pattern = this_pattern
			}
			$(this).datepicker({
				dateFormat : pattern,
				showOtherMonths : true
			});
				
			
		});
	}
	if ($.datepicker){
		$(".edit_datetimepicker").each(function(){
			var pattern = 'dd/mm/yy';
			var this_pattern = $(this).attr('pattern');
			if (this_pattern){
				pattern = this_pattern
			}
			$(this).datetimepicker({
				dateFormat : pattern,
				showOtherMonths : true
			});
				
			
		});
	}
 	$(".submit-tag").click(function(){
 			var ojb = $("#blogtagForm").find("input[name='name']");
 			var name= ojb.val();
 			if (!name){
 				alert('Please provide a tag name');
 				ojb.focus();
 	 			return ; 				
 			}
   			$.ajax({
 				url : "/admin/blog-tag/create/",
 				type : "POST",
 				data : $('#blogtagForm').serialize(),
 				dataType : "json",
 				success : function(data){		
 					if(data && data.state && (data.state.indexOf("ERROR") != -1)){
  						alert(data.message);
 						return;
 					}else{
 						$('<a>',{
	 							href : '#',
 	 							selectId : data.entity.id,
	 							text : data.entity.name,
	 						}).addClass('selectTag').appendTo($('.tags'));
 
 					}
 				}
 			});
  	});
 	
 	function formatCover(state){
 		if (state.element.length > 0){
 			if ($(state.element[0]).attr("coverURL")){
 	 		 	return '<p class="select-title">'+ state.text+'</p>    <img class="select-img" src="'+$(state.element[0]).attr("coverURL")+'" alt="Image">';
 			}else{
 	 			return state.text;
 			}
  		}else{
 			return state.text;
 		}
  	}
 	if ($('.related-blog').length > 0){
 		var target = $('.related-blog');
 		$.ajax({
				url : "/admin/category-post/list-all-by-category/?_="+ new Date().getTime(),
				type : "GET",
				dataType : "json",
				success : function(data){		
					if(data && data.state && (data.state.indexOf("ERROR") != -1)){
						alert(data.message);
						return;
					}else{
						
						$(data).each(function(step,entity){
							var optGroup = $("<optgroup>").attr("label",entity.name);
								$(entity.categoryPosts).each(function(step, post){
   									if (entityId != post.id){
   										
									var op = $("<option>").text(post.title).val(post.id).attr("coverURL",post.coverURL);
 									op.appendTo(optGroup);
									}
 								});
							optGroup.appendTo(target);	
 						})
 						
 						var maximumSelectionSize = target.attr("maximumSelectionSize");
						maximumSelectionSize = (maximumSelectionSize)?maximumSelectionSize:4
  						target.val(selectedRelated).select2({
  							maximumSelectionSize: maximumSelectionSize,
 							formatResult : formatCover,
 						    formatSelection: formatCover,
 						    escapeMarkup: function(m) { return m; }
  						});
						
 					}
				}
			});
 		
 	}
 		
 	if ($('.tags').length > 0){
 			$.ajax({
 				url : "/admin/blog-tag/%7B%22groupOp%22:%22AND%22,%22rules%22:[]%7D/views/?pageNo=1&pageSize=999&order=asc&orderBy=count&_="+ new Date().getTime(),
 				type : "GET",
  				dataType : "json",
 				success : function(data){		
 					if(data && data.state && (data.state.indexOf("ERROR") != -1)){
  						alert(data.message);
 						return;
 					}else{
 						
 						$(data.result).each(function(step,entity){
   	 						$('<a>',{
 	 							href : '#',
 	 							text : entity.name,
 	 						   selectId : entity.id,
  	 						}).addClass('selectTag').appendTo($('.tags'));
  						})
   						if (typeof(selectedIds) == "undefined"){
  							
  						}else{
  						$(selectedIds).each(function(step,value){
  							var selectTag = $(".selectTag[selectId='"+value+"']");		
   							selectTag.addClass('topen');
   						}); 
  						}
  						 
  					}
 				}
 			});
  	}
 	
 	
 	$(document).on('click','.selectTag', function() {
  		$(this).toggleClass('topen');
 	    return false;
 	});
  	
 	
 	
 	
 	
	
	
	
	$('a').click(function(event) {
		event.preventDefault();
	});
	CKEDITOR.on('instanceReady', function(evt) {
		var editor = evt.editor;
		CKFinder.setupCKEditor(editor, {
			basePath : '/ckfinder/',
			skin : 'v1'
		});

	});

	$('.dashboard').click(function(event) {
		window.location = "/admin/dashboard/";
	});
	$('.go-back').click(function(event) {
		window.history.back();
	});


	$('.forsubmit').click(function(event) {
		var data = [];
		if ($('.topedit2').length > 0) {
			data = $.merge($('.topedit2 :input').serializeArray(), data);
		}
		if ($('.topedit').length > 0) {
			data = $.merge($('.topedit :input').serializeArray(), data);
		}
		//
		if (typeof (tid) != 'undefined') {
			data = $.merge([ {
				name : 'tid',
				value : tid
			} ], data);
		}

		for ( var i in CKEDITOR.instances) {
 
 			
			
			if (i.indexOf('image') >= 0 || i == 'coverURL' || i == 'picURL' ||  $(CKEDITOR.instances[i].element).attr('pure_image')) {
 				var obj = $(CKEDITOR.instances[i].getData());
 				var xx = $('img', obj);
				data = $.merge([ {
					name : i,
					value : xx.attr('src')
				} ], data);
			}else if (i == 'title' || $(CKEDITOR.instances[i].element).attr('pure_text')){
				var obj = $(CKEDITOR.instances[i].getData());
 				data = $.merge([ {
					name : i,
					value : obj.text()
				} ], data);
 			}
			else {
				data = $.merge([ {
					name : i,
					value : CKEDITOR.instances[i].getData()
				} ], data);
			}
		}
		
		var tags =$('.selectTag.topen');
		if (tags.length>0){
 		$(tags).each(function(step ,value){
 		
 			
 		
 		data = $.merge([ {
			name : 'tagIds[]',
			value : $(value).attr('selectid')
		} ], data);
		});
 		}
		
		var related = $('.related-blog');
		if (related.length >0){
			
			$(related.select2("val")).each(function(step ,value){
 		 		data = $.merge([ {
					name : 'relatedIds[]',
					value : value
				} ], data);
			});
 		}
 
 	
		var submit = {
			type : "POST",
			data : data,
			dataType : "json",
			success : function(data) {
				if (data && data.state && (data.state.indexOf("ERROR") != -1)) {
					alert(data.message);
					return;
				} else {
					if (data.entity){
						url = data.entity;
 					}
					alert("update successfully");
				}
			}
		};
		if (url){
			submit.url = url;
 		}
		$.ajax(submit);
	});
});